package easymall.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import easymall.po.User;
import easymall.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@RequestMapping("/login")
	public String login(User user,HttpSession session,Model model) {
//		System.out.println(user);
		User user1=userService.login(user.getUsername());
		if (user1==null) {
			model.addAttribute("message","输入的用户名出错");
			return "login";
		}
		else if(user1.getPassword().equals(user.getPassword())){
			session.setAttribute("user", user1);
			return "redirect:/index.jsp";
		}
		else {
			model.addAttribute("message","输入的用户名或密码出错");
			return "login";
		}
	}
	
	@RequestMapping("/checkUser")
	public void checkUser(String username,HttpServletResponse response) throws IOException {
		if (userService.login(username)!=null) {
			response.getWriter().print("您输入的用户名已被注册");
			
		}else
		{
			response.getWriter().print("您输入的用户名可以使用");
		}
	}
	
	@RequestMapping("/regist")
	public String regist(User user,String idcode,HttpSession session,Model model) {
		System.out.println(user);
		if("".equals(user.getUsername())|| user.getUsername()==null) {
			model.addAttribute("msg","用户名不能为空");
			return "regist";
		}
		if("".equals(user.getPassword())|| user.getPassword()==null) {
			model.addAttribute("msg","密码不能为空");
			return "regist";
		}
		if(!session.getAttribute("idcode").equals(idcode)) {
			System.out.println(session.getAttribute("idcode"));
			System.out.println(session.getAttribute("idcode")==idcode);
			System.out.println("out->"+idcode);
//			session.setAttribute("idcodeMsg", "验证码错误！");
			model.addAttribute("msg","验证码错误！");
			return "regist";
		}

		if (userService.login(user.getUsername())!=null) {
			model.addAttribute("msg","不能重复注册");
			return "regist";
		}
		
		if (userService.regist(user)>0) {
			model.addAttribute("msg","注册成功");
			return "login";
		}
		else {
			model.addAttribute("msg","注册失败");
			return "regist";
		}
		
	}
}
